import { verifyReaderCardId } from "@/model/readerCard/readerCard";
import { request, catchException } from "@/util/request";

async function getPointBill(filter: Api.IListFilter, need: boolean = true) {
  let bill = { score: 0, data: [] as any[] };
  if (need) {
    try {
      const res = await request({
        url: "wechat/userInfo/scoreList",
        data: { ...filter, token: true },
      });
      bill = res.data.content;
    } catch (error) {
      catchException(error);
    }
    return bill;
  }
  if (!verifyReaderCardId(true)) return bill;
  try {
    const res = await request({
      url: "wechat/userInfo/scoreList",
      data: { ...filter, token: true },
    });
    bill = res.data.content;
  } catch (error) {
    catchException(error);
  }
  return bill;
}
async function getUserAddrList(filter: Api.IListFilter) {
  let addrList = [];
  try {
    const res = await request({
      loading: false,
      url: "wechat/userAddress/list",
      data: { ...filter, token: true },
    });
    addrList = res.data.content.data;
  } catch (error) {
    catchException(error);
  }
  return addrList;
}
async function worksVote(item: any, detail: any) {
  const presentTime = new Date().getTime();
  const { vote_start_time, vote_end_time, vote_number, vote_way } = detail;
  const endTime = new Date(vote_end_time?.replace(/-/g, "/")).getTime();
  const startTime = new Date(vote_start_time?.replace(/-/g, "/")).getTime();
  if (presentTime < startTime) {
    uni.showToast({ title: "投票未开始", icon: "none", duration: 2000 });
    return;
  }
  if (presentTime > endTime) {
    uni.showToast({ title: "投票已结束", icon: "none", duration: 2000 });
    return;
  }
  if (+vote_number <= 0) {
    const msg = +vote_way === 1 ? "投票已达到上限" : "今日投票已达上限";
    uni.showToast({ title: msg, icon: "none", duration: 2000 });
    return;
  }
  try {
    let res = await request({
      url: "wechat/contestActivity/worksVote",
      loadingText: "投票中",
      method: "POST",
      data: { works_id: item.id, token: true },
    });
    uni.showToast({ title: res.data.msg, icon: "none", duration: 2000 });
    detail.vote_number -= 1;
    item.user_vote_num += 1;
    item.vote_num += 1;
  } catch (error) {
    catchException(error);
  }
}

export { getPointBill, getUserAddrList, worksVote };
